package cn.lucky.springcloud.controller;

import cn.lucky.springcloud.entities.CommonResult;
import cn.lucky.springcloud.entities.Payment;
import cn.lucky.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;


/**
 * @author lingpeng.jiang
 * @create 2020-11-30-23:46
 */
@RestController
@Slf4j
public class PaymentController {

    @Autowired
    private PaymentService paymentService;

    @Value("${server.port}")
    private String serverPost;

    @PostMapping("/payment/create")
    public CommonResult<Integer> create(@RequestBody Payment payment){
        int result = paymentService.create(payment);
        if (result > 0){
            log.info("插入数据到数据库成功");
            return new CommonResult<>(200,"插入数据库成功",result);
        } else {
            log.info("插入数据到数据库失败");
            return new CommonResult<>(444,"插入失败",null);
        }
    }

    @GetMapping("/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id){
        Payment payment = paymentService.getPaymentById(id);
        if (payment != null){
            log.info("查询成功");
            return new CommonResult<>(200,"查询成功,serverPort:" + serverPost,payment);
        } else {
            log.info("查询失败");
            return new CommonResult<>(444,"查询失败,ID为" + id,null);
        }
    }


    @GetMapping("/payment/list")
    public CommonResult<Payment> queryPayment(){
        List<Payment> payments = paymentService.queryPayment();
        if (payments != null){
            log.info("查询成功");
            return new CommonResult<>(200,"查询成功,serverPort:" + serverPost,payments.get(0));
        } else {
            log.info("查询失败");
            return new CommonResult<>(444,"查询失败",null);
        }
    }


    /**
     * 测试自定义负载策略算法
     * @return
     */
    @GetMapping("/payment/lb")
    public String consumerBalancerRule(){
        return serverPost;
    }


    /**
     * 测试openFeign的超时控制
     * @return
     */
    @GetMapping("/payment/openfeign/timeout")
    public String testOpenfeignTimeOut(){
        try {
            TimeUnit.SECONDS.sleep(3);
        }catch (Exception e){
            e.printStackTrace();
        }
        return serverPost;
    }
}
